﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Xml;
using System.Xml.Serialization;
using bmapi.HelperClass;
using bmapi.Models.CADModel;
using bmapi.Models.DataEntity;

namespace bmapi.Controllers
{
    public class CAD33Controller : CADFinishController
    {
        /// <summary>
        /// 导入生产单   
        /// </summary> 
        /// <param name="json">id process go upload file文件名/文件夹名 extname扩展名  TDxml文件路径 </param>
        [HttpPost, Route("cad33/Finish")]
        public string Finish(dynamic json)
        {

            WriteDebug("cad33/Finish", "1");
            if (json == null)
                return ReturnError(201, "没有可执行参数");
            string filename = json.file.ToString();
            int upload = Convert.ToInt32(json.upload);

            int loginid = GetCrrentIDByToken();
            User user = GetUserByLoginID(loginid);

            WriteDebug("cad33/Finish", "2");

            if (user == null)
                return ReturnError(201, "不存在当前工号为" + loginid + "的用户");

            string xmlpath = GetPCPath(json.name.ToString()) + "\\" + filename;

            WriteDebug("cad33/Finish", "3");

            if (!File.Exists(xmlpath))
                return ReturnError(201, "找不到路径" + xmlpath);

            #region  读取xml文件数据 样式名，订单号，ERP中的ID(orderId),生产件数
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlpath);

            WriteDebug("cad33/Finish", "4");

            string modelName = doc.GetElementsByTagName("modelName")[0].InnerText;
            string orderName = doc.GetElementsByTagName("orderName")[0].InnerText;
            XmlNodeList xmllist = doc.GetElementsByTagName("orderID");
            string orderId = "";
            if (xmllist.Count > 0)
                orderId = xmllist[0].InnerText;
            int number = Convert.ToInt32(doc.GetElementsByTagName("number")[0].InnerText);

            WriteDebug("cad33/Finish", "5");

            #endregion

            if (string.IsNullOrEmpty(modelName) || string.IsNullOrEmpty(orderName) || number < 0)
                return ReturnError(201, "给的数据不完整,样式名:" + modelName + "，订单号:" + orderName + "，ERP中的ID:" + orderId + ",生产件数:" + number);
            WriteDebug("cad33/Finish", "6");
            if (CheckOrdername(orderName))
            {
                WriteDebug("cad33/Finish", orderName + "该生产单号已经存在");
                return ReturnError(201, orderName + "该生产单号已经存在");
            }
            else
            {
                if (AddOrderAndPC(user, modelName, orderName, orderId, number, doc) == 0)
                {
                    WriteDebug("cad33/Finish", "7");
                    return ReturnError(201, "数据操作出错");

                }
            }
            return ReturnError(200, "OK");
        }

        /// <summary>
        /// 添加生产单信息 
        /// </summary> 
        /// <param name="loginid"></param>
        /// <param name="modelName"></param>
        /// <param name="orderName"></param>
        /// <param name="orderID"></param>
        /// <param name="number"></param>
        /// <returns></returns>
        private int AddOrderAndPC(User user, string modelName, string orderName, string orderID, int number, XmlDocument doc)
        {

            string[] minfo = GetMaterialInfo(doc);
            try
            {
                string sql = "";
                List<SQLCommand> cmds = new List<SQLCommand>();
                int id = GetNewSafeID(user.login_id);
                if (user == null)
                    return 0;
                #region  新增订单   
                SQLCommand sc = new SQLCommand("select id from Model_tb where name=@name", "@name", modelName);
                int modelid = Convert.ToInt32(sc.ExecuteScalar());
                WriteDebug("AddOrderAndPC", "modelid:"+modelid);
                //PLID是当前用户对应的吗  暂时这样做处理  model_id 根据样板名从Model_tb表中获取 erpid为表中的orderID ername样板名 lsh流水号暂认为0
                //流水号  LSH LSH_tb中erpID指用户id即工号 根据用户id获取流水号
                sql = "insert into Order_tb values(@id,@name,@createid,@createtime,@finishtime,@plid,@modelid,0,' ',@erpid,@erpname,' ',' ',0,0,0,@lsh,0,@number,1,@erpcustname,@mcode,@mcolor)";
                sc = new SQLCommand(sql);
                sc.Add("@id", id);
                sc.Add("@name", orderName);
                sc.Add("@createid", user.login_id);
                sc.Add("@createtime", DateTime.Now);
                sc.Add("@finishtime", DateTime.Now.AddMonths(2));
                sc.Add("@plid", user.PLID);
                sc.Add("modelid", modelid);
                sc.Add("@erpid", orderID);
                sc.Add("@erpname", modelName);
                sc.Add("@lsh", 0);
                sc.Add("@number", number);                
                sc.Add("@mcode", minfo[0]);
                sc.Add("@mcolor", minfo[1]);
                sc.Add("@erpcustname", minfo[2]);
                cmds.Add(sc);
                WriteDebug("AddOrderAndPC", "Order插入语句");
                #endregion
                #region  添加流程
                sql = "insert into PC_tb(path,pc_id,PLID,maxStep,step,model_id,grouping) values(@path,@pcid,@plid,@maxstep,@step, @model_id,@grouping)";
                sc = new SQLCommand(sql);
                sc.Add("@path", orderName);
                sc.Add("@pcid", id);
                sc.Add("@plid", user.PLID);
                sc.Add("@maxstep", user.code);
                sc.Add("@step", GetNextProcessID(user.PLID, user.code));
                sc.Add("@model_id", modelid);
                sc.Add("@grouping", user.grouping);
                cmds.Add(sc);
                WriteDebug("AddOrderAndPC", "PC_tb插入语句");
                #endregion
                int rtn = SQLCommand.ExecTran(cmds);
                
                if (rtn == 1)
                {
                    WriteDebug("AddOrderAndPC", "新增Order与PC记录成功 rtn:"+rtn);
                    AddTask(33, id);
                    AddLSH(doc, id);
                }
                return rtn;
            }
            catch (Exception e)
            {

                WriteLog("AddOrderAndPC", e.Message);
                return 0;
            }

        }

        private string[] GetMaterialInfo(XmlDocument doc)
        {
            XmlNodeList fabrics = doc.GetElementsByTagName("fabric");
            //物料可能有多个或者没有暂时取第一个 客户名没有暂时为空
            string mcode = "";
            string mcolor = "";
            string erpcustname = "";
            string[] minfo = new string[] {mcode,mcolor,erpcustname };
            if (fabrics.Count > 0)
            {
                for (int i = 0; i < 1; i++)
                {
                    foreach (XmlNode item in fabrics[i])
                    {
                        if (item.Name.Equals("code"))
                            if (item.InnerText != null)
                                minfo[0] = item.InnerText;
                        if (item.Name.Equals("color"))
                            if (item.InnerText != null)
                                minfo[1] = item.InnerText;
                        if (item.Name.Equals("custname"))
                            if (item.InnerText != null)
                                minfo[2] = item.InnerText;
                    }
                }
            }
            return minfo;
        }
        

        /// <summary>
        /// 添加流水号
        /// </summary>
        /// <param name="erpId">erpids是XML中的person的ID   用户（人）的ID	整数</param>     
        /// <param name="orderid">流程</param>
        /// <param name="usrename">用户的姓名	最大6个字符</param>
        /// <param name="pod">Pod文件的文件名</param>
        private void AddLSH(XmlDocument doc,int orderid)
        {
            try
            {
                XmlNodeList persons = doc.GetElementsByTagName("person");
                List<SQLCommand> cmds = new List<SQLCommand>();
                string sql = "insert into LSH_tb values(@orderid,@name,@erpid,@pod,@lsh,@copys)";
                
                if (persons.Count > 0)
                {
                    for (int i = 0; i < persons.Count; i++)
                    {
                        SQLCommand sc = new SQLCommand(sql);
                        foreach (XmlNode node in persons[i])
                            AddLSH(node, sc);

                        sc.Add("@orderid", orderid);
                        sc.Add("@lsh", 0);
                        cmds.Add(sc);
                    }
                    if (SQLCommand.ExecTran(cmds) == 1)
                        WriteDebug("AddLSH", "新增成功");
                    else
                        WriteDebug("AddLSH", "新增失败");
                }
            }
            catch (Exception e)
            {
                WriteDebug("AddLSH","新增LSH记录失败,"+e.Message);
            }          
            
        }

        private void AddLSH(XmlNode node,SQLCommand sc)
        {
            if (node.Name.Equals("ID"))
            {
                AddInt(sc, "@erpid", node);
            }
            else if (node.Name.Equals("name"))
            {
                AddString(sc, "@name", node);
            }
            else if (node.Name.Equals("pod"))
            {
                AddInt(sc, "@pod", node);
            }
            else if (node.Name.Equals("copys"))
                AddInt(sc, "@copys", node);
        }

    }
}
